package com.ruoyi.plugs.web.controller.system;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.plugs.common.exception.BusinessException;
import com.ruoyi.plugs.framework.aspect.CountResponseTimeAspect;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerGroup;
import org.springframework.boot.logging.LoggerGroups;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@Controller
@RequestMapping("/system/webLog")
public class WebLogController extends BaseController {
    private String prefix = "plugs/system/webLog";
    @Autowired
    private LoggingSystem loggingSystem;
    @Autowired
    private RuoYiConfig ruoYiConfig;
    @Autowired
    private LoggerGroups loggerGroups;

    @RequiresPermissions("monitor:webLog:view")
    @GetMapping()
    public String costTime(ModelMap modelMap) {
        return prefix + "/webLog";
    }

    @GetMapping(value = "/file", produces = "text/plain; charset=UTF-8")
    @ResponseBody
    @RequiresPermissions("monitor:webLog:view")
    public Resource logFile(@RequestParam(required = false) String filePath) {
        if (ruoYiConfig.isDemoEnabled()&&StrUtil.isNotBlank(filePath)) {
            throw new BusinessException("演示环境，禁止修改模式文件路径");
        }

        String lookFilePath = ruoYiConfig.getLogFilePath();
        if (StrUtil.isNotBlank(filePath)) {
            lookFilePath = filePath;
        }
        if(StrUtil.isEmpty(lookFilePath)){
            return null;
        }
        Resource logFileResource = new FileSystemResource(new File(lookFilePath));
        if (logFileResource == null || !logFileResource.isReadable()) {
            return null;
        }
        return logFileResource;
    }

    @GetMapping(value = "/level") //动态设置日志级别
    @ResponseBody
    @RequiresPermissions("monitor:webLog:update")
    public AjaxResult configureLogLevel(String name, LogLevel configuredLevel) {
        if (StrUtil.isBlank(name)) {
            throw new BusinessException("请输入日志名称");
        }
        LoggerGroup group = this.loggerGroups.get(name);
        if (group != null && group.hasMembers()) {
            group.configureLogLevel(configuredLevel, this.loggingSystem::setLogLevel);
            return AjaxResult.success();
        }
        this.loggingSystem.setLogLevel(name, configuredLevel);
        return AjaxResult.success();
    }
}
